const express = require('express');
const router = express.Router();
const DownloadService = require('../services/downloadService');
const {
  validateAddDownload,
  validateTaskId,
  validateQueryParams,
  validateCleanupParams
} = require('../middleware/validation');

// 延迟创建下载服务实例（避免在命令行参数解析时启动服务）
let downloadService = null;

function getDownloadService() {
  if (!downloadService) {
    // 从全局变量获取配置（由app.js设置）
    const downloadDir = global.APP_CONFIG?.DOWNLOAD_DIR || process.env.DOWNLOAD_DIR;
    const cookie = global.APP_CONFIG?.ZLIB_COOKIE || process.env.ZLIB_COOKIE;

    downloadService = new DownloadService(downloadDir, cookie);
  }
  return downloadService;
}

/**
 * POST /api/download/add
 * 添加下载任务
 */
router.post('/add', validateAddDownload, async (req, res, next) => {
  try {
    const { url, customFileName } = req.body;
    const result = await getDownloadService().addDownloadTask(url, customFileName);
    res.json(result);
  } catch (error) {
    next(error);
  }
});

/**
 * GET /api/download/queue
 * 获取队列状态
 */
router.get('/queue', (req, res, next) => {
  try {
    const result = getDownloadService().getQueueStatus();
    res.json(result);
  } catch (error) {
    next(error);
  }
});

/**
 * GET /api/download/status/:id
 * 获取单个任务状态
 */
router.get('/status/:id', validateTaskId, (req, res, next) => {
  try {
    const { id } = req.params;
    const result = getDownloadService().getTaskStatus(id);
    res.json(result);
  } catch (error) {
    next(error);
  }
});

/**
 * DELETE /api/download/:id
 * 删除任务
 */
router.delete('/:id', validateTaskId, (req, res, next) => {
  try {
    const { id } = req.params;
    const result = getDownloadService().deleteTask(id);
    res.json(result);
  } catch (error) {
    next(error);
  }
});

/**
 * POST /api/download/:id/cancel
 * 取消任务
 */
router.post('/:id/cancel', validateTaskId, (req, res, next) => {
  try {
    const { id } = req.params;
    const result = getDownloadService().cancelTask(id);
    res.json(result);
  } catch (error) {
    next(error);
  }
});

/**
 * POST /api/download/:id/retry
 * 重试任务
 */
router.post('/:id/retry', validateTaskId, (req, res, next) => {
  try {
    const { id } = req.params;
    const result = getDownloadService().retryTask(id);
    res.json(result);
  } catch (error) {
    next(error);
  }
});

/**
 * GET /api/download/history
 * 获取下载历史
 */
router.get('/history', validateQueryParams, (req, res, next) => {
  try {
    const { limit = 50, status } = req.query;
    const result = getDownloadService().getDownloadHistory(limit, status);
    res.json(result);
  } catch (error) {
    next(error);
  }
});

/**
 * POST /api/download/cleanup
 * 清理历史任务
 */
router.post('/cleanup', validateCleanupParams, (req, res, next) => {
  try {
    const { maxAge = 7 } = req.body;
    const result = getDownloadService().cleanupHistory(maxAge);
    res.json(result);
  } catch (error) {
    next(error);
  }
});

/**
 * GET /api/download/stats
 * 获取服务统计信息
 */
router.get('/stats', (req, res, next) => {
  try {
    const result = getDownloadService().getServiceStats();
    res.json(result);
  } catch (error) {
    next(error);
  }
});

/**
 * GET /api/download/health
 * 健康检查
 */
router.get('/health', (req, res) => {
  res.json({
    success: true,
    status: 'healthy',
    timestamp: new Date().toISOString(),
    uptime: process.uptime(),
    memory: process.memoryUsage()
  });
});

// 优雅关闭处理
process.on('SIGTERM', () => {
  console.log('收到SIGTERM信号，正在关闭下载服务...');
  if (downloadService) {
    downloadService.destroy();
  }
  process.exit(0);
});

process.on('SIGINT', () => {
  console.log('收到SIGINT信号，正在关闭下载服务...');
  if (downloadService) {
    downloadService.destroy();
  }
  process.exit(0);
});

module.exports = router;
